//
//  LEDataInputStream.m
//  UMDReader
//
//  Created by 张 霄鹤 on 10-1-9.
//  Copyright 2010 xhzhang. All rights reserved.
//

#import "LEDataInputStream.h"


@implementation LEDataInputStream

- (id)initWithData:(NSData *)d{
	if(self = [super init]){
		_data = [d retain];
		_buf = (char *)[_data bytes];
		eof = NO;
		_length = [_data length];
	}
	return self;
}

/**
 * 重新设置数据，并且位置设置为0
 */
- (void)reset:(NSData *)d{
	[_data release];
	_data = [d retain];
	_buf = nil;
	_buf = (char *)[d bytes];
	eof = NO;	
	_length = [_data length];
}

- (NSInteger)read{
	NSInteger ch = -1;
	if(!eof){
		if(_pos < _length){
			ch = (NSInteger)_buf[_pos++];
			if(ch < 0){
				ch &= 0x0ff;
			}
		}
	}
	return ch;
}

- (short)readShort{
	short ret = -1;
	if(!eof){
		NSInteger l = [self read];
		if(l != -1){
			NSInteger h = [self read];
			if(h != -1){
				ret = ((h & 0x0ff)<<8 | (l & 0x0ff));
			}
		}
	}
	return ret;
}

- (NSInteger)readInt{
	NSUInteger ret = -1;
	if(!eof){
		NSInteger ll = [self read];
		if(ll != -1){
			NSInteger lh = [self read];
			if(lh != -1){
				NSInteger hl = [self read];
				if(hl != -1){
					NSInteger hh = [self read];
					if(hh != -1){
						ret = ((hh & 0x0ff)<<24) | ((hl &0x0ff)<<16) | ((lh &0x0ff) << 8) | (ll & 0x0ff);
					}
				}
			}
		}
	}
	return ret;
}

- (NSInteger)readBytes:(char *)buf withLength:(NSInteger)length{
	NSInteger ret = -1;
	if(!eof){
		if(_pos < _length){
			if(_pos + length <= _length){
				[_data getBytes:buf range:(NSMakeRange(_pos, length))];
				_pos += length;
				ret = length;
			}else{
				[_data getBytes:buf range:(NSMakeRange(_pos, _length - _pos))];
				eof = YES;
				ret = _length - _pos;
				_pos = _length;
			}
		}else{
			eof = YES;
		}
	}
	return ret;
}

- (char *)getCurrentBytesRefwithLength:(NSInteger)length retLength:(NSInteger *)rlen{
	*rlen = -1;
	char *buf = nil;
	if(!eof){
		if(_pos < _length){
			if(_pos + length <= _length){
				buf = &_buf[_pos];
				_pos += length;
				*rlen = length;
			}else{
				// [_data getBytes:buf range:(NSMakeRange(_pos, _length - _pos))];
				*rlen = _length - _pos;
				buf = &_buf[_pos];
				eof = YES;
				_pos = _length;
			}
		}else{
			eof = YES;
		}
	}
	return buf;
}

- (NSInteger)skip:(NSInteger)length{
	NSInteger ret = -1;
	if(!eof){
		if(_pos < _length){
			if(_pos + length <= _length){
				// [_data getBytes:buf range:(NSMakeRange(_pos, length))];
				_pos += length;
				ret = length;
			}else{
				// [_data getBytes:buf range:(NSMakeRange(_pos, _length - _pos))];
				eof = YES;
				ret = _length - _pos;
				_pos = _length;
			}
		}else{
			eof = YES;
		}		
	}
	return ret;
}

- (void)dealloc{
	[_data release];
	_buf = nil;
	[super dealloc];
}

@end
